package com.peanut.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")//  /*代表拦截所有路径
public class Filter implements javax.servlet.Filter {

    /**
     * servlet 的生命周期
     * 被创建
     * 默认情况第一次访问时被创建
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 如果这里面不做任何代码的编写那就不会跳转，不会放行
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        //乱码
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");//请求编码格式为utf-8
        resp.setCharacterEncoding("UTF-8");//响应编码格式为utf-8
        resp.setContentType("text/json;charset=utf-8");//解决传值乱码
        resp.setHeader("Access-Control-Allow-Origin", "*");

         String url = req.getRequestURI();
        System.out.println("url = " + url);
//        url.equals("/login")||url.equals("/userAdd")
        if (true){
            filterChain.doFilter(req,resp);

        }
//        if (url.endsWith("/back/backHome.html")){
//            HttpSession session = req.getSession();
//            Object username = session.getAttribute("username");
//            if (username==null){  // 未登录
//                resp.sendRedirect("/login");
//            }else {
//                filterChain.doFilter(req,resp);
//            }
//        }

        //如果在session里面取得的用户名为空，则表示需要重新登录
    }

    /**
     * 被销毁
     */
    @Override
    public void destroy() {

    }
}
